package top.eggcode.modules.user.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.eggcode.component.query.CriteriaBuilder;
import top.eggcode.modules.user.model.AccountEntity;
import top.eggcode.modules.user.model.AccountRoleEntity;
import top.eggcode.modules.user.model.RoleEntity;
import top.eggcode.modules.user.store.AccountRoleRepository;
import top.eggcode.modules.user.store.AccountStore;
import top.eggcode.base.BaseServiceImpl;

import java.util.LinkedList;
import java.util.List;

/**
 * Title:
 * Description: TODO
 * Date: 2021/8/7 15:30
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Service
public class AccountRoleService extends BaseServiceImpl<AccountRoleEntity> {

    private final AccountRoleRepository accountRoleRepository;

    private final AccountStore accountStore;

    private final RoleService roleService;

    private final CriteriaBuilder builder;

    /**
     * 查找列表
     *
     * @param accountId 账户id
     * @return 角色列表
     */
    public List<RoleEntity> listRole(String accountId) {
/*        List<AccountRoleDO> relationList = accountRoleRepository.findByAccountId(accountId);
        List<RoleDO> roleList = new LinkedList<>();
        relationList.forEach(relation -> {
            roleService.get(relation.getRoleId()).ifPresent(roleList::add);
        });*/

        List<RoleEntity> roleList = builder.createQuery(RoleEntity.class)
                .fromEntity("root")
                .leftJoin("auth_account_role", "relation", "relation.role_id = root.id")
                .where(condition -> {
                    condition.eq("relation.account_id", accountId);
                })
                .fetch();

        return roleList;
    }

    /**
     * 查找列表
     *
     * @param roleId 账户id
     * @return 账户列表
     */
    public List<AccountEntity> listAccount(String roleId) {
        List<AccountRoleEntity> relationList = accountRoleRepository.findByAccountId(roleId);
        List<AccountEntity> accountList = new LinkedList<>();
        relationList.forEach(relation -> {
            accountStore.findById(relation.getRoleId()).ifPresent(accountList::add);
        });
        return accountList;
    }

    public void saveRoles(String accountId, List<RoleEntity> roles) {
        roles.forEach(role -> {
            AccountRoleEntity relation = new AccountRoleEntity();
            relation.init();
            relation.setRoleId(role.getId());
            relation.setAccountId(accountId);
            super.put(relation);
        });
    }

    public void clearRoles(String accountId) {
        this.accountRoleRepository.batchDeleteByAccount(accountId);
    }
}
